package org.example.JMS1.producer;

import lombok.SneakyThrows;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class QueueProducer {
    public static final String USER_NAME = ActiveMQConnection.DEFAULT_USER;
    public static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;

    public static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

    @SneakyThrows
    public static void runQueueProducer() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USER_NAME, PASSWORD, BROKER_URL);
        Connection connection = connectionFactory.createConnection();
        connection.start();

        /**
         * true、false 是否使用事务
         * AUTO_ACKNOWLEDGE：自动确认 一旦接收方应用程序的消息处理回调函数返回，会话对象就会确认消息的接收
         * 一般接收方的做法是调用consumer.setMessageListener()注册消息处理函数
         * CLIENT_ACKNOWLEDGE：客户端确认模式。会话对象依赖于应用程序对被接收的消息调用一个acknowledge()方法
         * DUPS_OK_ACKNOWLEDGE：有副本的客户端确认消息机制
         * SESSION_TRANSACTED：
         * AUTO_ACKNOWLEDGE：
         */
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        // 创建队列，指定队列名称，消费者生产者根据队列发送接收数据
        Queue activeMq01 = session.createQueue("activeMq-queue-01");
        MessageProducer producer = session.createProducer(activeMq01);
        // 消息
        TextMessage message = session.createTextMessage("abcdefg");
        // 发送消息
        producer.send(message);
        // 提交事务
        session.commit();
        session.close();
        connection.close();
    }
}
